<template>
  <app-dialog-form
      title="消息回复"
      :confirm="handleSubmit"
      @open="handleDialogOpen"
      @closed="handleDialogClosed"
  >
    <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >
      <el-form-item label="头像" prop="nickName">
        <app-avatar :size="45" :src="formData.avatar"/>
      </el-form-item>
      <el-form-item label="账号" prop="from">
        <el-input disabled v-model="formData.from" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input disabled v-model="formData.nickName" placeholder="请输入联系人姓名"/>
      </el-form-item>
      <el-form-item label="消息内容" prop="message">
        <div style="color: #8c939d;font-size: 12px;">注：使用当前消息接收者账号代替回复</div>
        <el-input :rows="10"  maxlength="200" show-word-limit type="textarea" v-model="formData.message" placeholder="请输入消息"/>
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import {PropType, ref} from 'vue';
import type {IElForm, IFormRule} from '@/types/element-plus';
import {ElMessage} from 'element-plus';
import {IChatMessage} from "@/api/types/chat";
import {getChatUser,sendMessage} from "@/api/chat";

const props = defineProps({
  chatItem: {
    type: Object as PropType<IChatMessage>,
    default: () => {
    },
  },
});

interface EmitsType {
  (e: 'success'): void;
}

const emit = defineEmits<EmitsType>();

const form = ref<IElForm | null>(null);
const formLoading = ref(false);
const formData = ref<IChatMessage>({});

const formRules: IFormRule = {
  message: [{required: true, message: '请输入消息内容', trigger: 'blur'}],
};
const handleDialogOpen = async () => {
  formLoading.value=true
  const userInfo =await getChatUser(props.chatItem?.to!)
  formData.value.nickName=userInfo.nickName
  formData.value.avatar=userInfo.avatarUrl
  formData.value.to=props.chatItem?.from
  formData.value.from=props.chatItem?.to
  formLoading.value=false
};


const handleDialogClosed = () => {
  formData.value = {}
  form.value?.clearValidate(); // 清除验证结果
  form.value?.resetFields(); // 清除表单数据
};

const handleSubmit = async () => {
  const valid = await form.value?.validate();
  if (!valid) {
    return;
  }
  formLoading.value=true
  await sendMessage(formData.value)
  formLoading.value=false
  emit('success');
  ElMessage.success('消息回复成功！');
};

</script>


<style lang="scss" scoped>

</style>
